/*
* 四川生学教育科技有限公司
* Copyright (c) 2015-2025 Founder Ltd. All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Founder. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the agreements
* you entered into with Founder.
*
*/
package cn.demo.zookeeper.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.Watcher.Event.EventType;

import java.util.concurrent.CountDownLatch;

/**
 * @author WUANG (wa@sxw.cn)
 * @description CuratorTest
 * @date 2018/11/1 16:10
 * @slogon 站在巨人的肩膀上
 * @since 2.0.0
 */
public class CuratorTest {
    static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String args[]) throws Exception {
        //
        // 与 127.0.0.1:2181 连接，重试策略：仅重试 1 次
        //
        CuratorFramework client = CuratorFrameworkFactory.newClient("120.78.169.174:2181", new RetryOneTime(1000));
        client.start();

        //
        // 判断 ZNode /2018-02 是否存在，设置 Watch
        //
        client.checkExists().usingWatcher((CuratorWatcher) (event) -> {
            if (event.getType() == EventType.NodeCreated) {
                System.out.println(Thread.currentThread().getName() + ": " + "node Created.");
            } else if (event.getType() == EventType.NodeDeleted) {
                System.out.println(Thread.currentThread().getName() + ": " + "node Deleted.");
            } else if (event.getType() == EventType.NodeDataChanged) {
                System.out.println(Thread.currentThread().getName() + ": " + "node Changed." + new String(client.getData().forPath("/username")));
            }

            countDownLatch.countDown();
        }).inBackground((c, event) -> {
            //
            // 异步接口
            //
            System.out.println(Thread.currentThread().getName() + ": " + "checkExists == " + event.getResultCode() + ", event == " + event.getType());
        }).forPath("/username");

        countDownLatch.await();
        System.out.println("terminate...");
    }
}